#!/bin/sh

e2e_test_install_pods() {
  echo 2
}

e2e_test(){
  run_test "Check cluster connectivity to primary postgres before resintall" check_primary_postgres_connectivity
  run_test "Check cluster connectivity to replica postgres before resintall" check_replica_postgres_connectivity
  run_test "Check cluster connectivity from outside the primary pod before resintall" check_outer_primary_connections
  run_test "Check cluster connectivity from outside the replica pod before resintall" check_outer_replica_connections

  run_test "Cluster reset" check_cluster_reset
  run_test "Check cluster connectivity to primary postgres" check_primary_postgres_connectivity
  run_test "Check cluster connectivity to replica postgres" check_replica_postgres_connectivity
  run_test "Check cluster connectivity from outside the primary pod" check_outer_primary_connections
  run_test "Check cluster connectivity from outside the replica pod" check_outer_replica_connections
  
  run_test "Check that reseted cluster is clean" check_cluster_clean
  run_test "Check database replication" check_cluster_replication

}

check_cluster_reset() {
  generate_mock_data
  check_mock_data

  DBOPS_NAME="$(get_sgdbops_name vacuum)"

  cat << EOF | kubectl create -f -
apiVersion: stackgres.io/v1
kind: SGDbOps
metadata:
  name: $DBOPS_NAME
  namespace: $CLUSTER_NAMESPACE
spec:
  sgCluster: $CLUSTER_NAME
  op: vacuum
EOF

  assert_dbops_completion "$DBOPS_NAME" "$CLUSTER_NAMESPACE"

  VACUUM_JOB_UID="$(kubectl get job -n "$CLUSTER_NAMESPACE" -l app=StackGresDbOps \
    --template '{{ range .items }}{{ printf "%s" .metadata.uid }}{{ end }}')"

  remove_cluster "$CLUSTER_NAME" "$CLUSTER_NAMESPACE"

  create_or_replace_cluster "$CLUSTER_NAME" "$CLUSTER_NAMESPACE" 2

  if [ "$VACUUM_JOB_UID" = "$(kubectl get job -n "$CLUSTER_NAMESPACE" -l app=StackGresDbOps \
    --template '{{ range .items }}{{ printf "%s" .metadata.uid }}{{ end }}')" ]
  then
    success "DbOps was not re-created"
  else
    fail "DbOps was re-created"
  fi

  wait_pods_running "$CLUSTER_NAMESPACE" 2
  wait_cluster "$CLUSTER_NAME" "$CLUSTER_NAMESPACE"
  switch_cluster_to_first "$CLUSTER_NAME" "$CLUSTER_NAMESPACE"
}

check_cluster_clean(){
  
  if exec_postgresutil 'psql -lqt | cut -d \| -f 1 | grep -qw "test"'
  then
    fail "Reset cluster is not clean"
  else
    success "Reset cluster is clean"
  fi
}

check_primary_postgres_connectivity(){
  check_connectivity -i 0
}

check_replica_postgres_connectivity(){
  check_connectivity -i 1
}

check_outer_primary_connections(){
  check_service_connectivity -i 1 -h "$CLUSTER_NAME"
}

check_outer_replica_connections(){
  check_service_connectivity -i 0 -h "$CLUSTER_NAME-replicas"
}

check_cluster_replication(){
  generate_mock_data
  check_mock_data_samehost "$CLUSTER_NAME"
  wait_until check_mock_data_replication "$CLUSTER_NAME"
}
